<template>
	<view>
		<view class="a my_canvas" id="my-canvas">
			<image class="my_draw_canvas" data-type="image" :data-url="'https://dy.sykj365.com/uploads/mini/bg@2x.png'" src="https://dy.sykj365.com/uploads/mini/bg@2x.png"></image>
			<view>
				<image src="https://dy.sykj365.com/uploads/mini/bg2@2x.png"></image>
				<image src="https://dy.sykj365.com/uploads/mini/bg2@2x.png"></image>
			</view>
		</view>
		<view @click="getSave">保存</view>
	</view>
</template>

<script>
	import Wxml2Canvas from 'wxml2canvas';
	
	export default {
		data() {
			return {
				coverData: {},
			}
		},
		methods: {
			getSave() {
				uni.showLoading();
				const that = this;
				const query = wx.createSelectorQuery().in(this);
				query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
					size: true,
					scrollOffset: true
				}, data => {
					let width = data.width;
					let height = data.height;
			
					that.coverData = {
						width,
						height
					}
			
					setTimeout(() => {
						that.startDraw();
					}, 500);
				}).exec();
			},
			startDraw() {
				let that = this;
			
				// 创建wxml2canvas对象
				let drawMyImage = new Wxml2Canvas({
					element: 'myCanvas', // canvas的id,
					obj: that, // 传入当前组件的this
					width: that.coverData.width * 2,
					height: that.coverData.height * 2,
					background: '#fff', // 生成图片的背景色
					logging: false, // 日志
					scrollY: 0,
					scrollX: 0,
					useCORS: true, //跨域
					allowTaint: true,
					progress(percent) { // 进度
						// console.log(percent);
					},
					finish(url) { // 生成的图片
						console.log(url);
						uni.hideLoading();
					},
					error(res) { // 失败原因
						console.log(res);
						uni.hideLoading();
						uni.showToast({
							icon: 'error',
							title: '画图失败，请重试',
							duration: 2000
						});
					}
				}, this);
				let data = {
					// 获取wxml数据
					list: [{
						type: 'wxml',
						class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名， **my_draw_canvas**单个元素的类名（所有要绘制的单个元素都要添加该类名）
						limit: '.my_canvas', // 要绘制的wxml元素根类名
						x: 0,
						y: 0
					}]
				}
				// 绘制canvas
				drawMyImage.draw(data, this);
			},
		}
	}
</script>

<style>
	.a {
		height: 1334rpx;
	}
</style>